package crap;

import java.awt.Dimension;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

import tools.ColorConversions;
import tools.Derivative;
import tools.Gauss;
import tools.ShowImage;

public class Aufgabe03a {
	public static void main(String[] args) {
		try {
			final BufferedImage kermit = ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("res/kermit001.jpg"));
			final int w = kermit.getWidth(), h = kermit.getHeight(), w2 = w/2, h2 = h/2;
			int n = 16;

			final BufferedImage bi = kermit.getSubimage(w2, h2, n, n);
			
			int[] pixels = bi.getRGB(0, 0, n, n, new int[n*n], 0, n);
			int[] lum = ColorConversions.getFastLuminance(pixels, new int[pixels.length]);
			pixels = ColorConversions.buildRGB(lum, lum, lum, pixels);
			bi.setRGB(0, 0, n, n, pixels, 0, n);
			
			int[] dx = Derivative.dx(lum, n, n, new int[lum.length]);
			int[] dy = Derivative.dy(lum, n, n, new int[lum.length]);
			
			double[] lengths = Derivative.getLengths(dx, dy, new double[dx.length]);
			double[] angles = Derivative.getAngles(dx, dy, new double[dx.length]);
			
			double[] kernel = Gauss.buildGaussianKernel(n, 1.5, new double[n*n]);
			
			for (int i = 0; i < kernel.length; i++) {
				lengths[i] *= kernel[i];
 			}
			
			ArrayList<double[]> descriptor = new ArrayList<double[]>();
			
			for (int j = 0; j<16; j+=4) {
				for (int i = 0; i<16; i+=4) {
					double[] histo = new double[8];
					for (int x = 0; x<4; x++) {
						for (int y = 0; y<4; y++) {
							double angle = angles[i+j*n+x+y*n];
							int index = (int)Math.floor(7.99999999*(angle+Math.PI)/(2*Math.PI));
							histo[index] += lengths[i+j*n+x+y*n];
						}
					}
					descriptor.add(histo);
				}
			}
			
			for (int i = 0; i<descriptor.size(); i++) {
				double[] bubu = descriptor.get(i);
				for (int j = 0; j<bubu.length; j++) {
					System.out.print(bubu[j]+" ");
				}
			}
			JFrame ff = new JFrame();
			ff.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			ShowImage si = new ShowImage(bi, AffineTransform.getScaleInstance(50,50));
			
			ff.add(si);
			ff.pack();
			ff.setVisible(true);
			
		}
		catch (IOException iox) {
			iox.printStackTrace();
		}
	}
}
